/**
 * @description axios封装类
 * @author 盘古他爹
 */

import axios from "axios"
import type { AxiosInstance } from "axios"
import { ElLoading } from "element-plus"
import { ILSRequestConfig, ILSRequestInterceptors } from "./types"
import { ILoadingInstance } from "element-plus/lib/components/loading/src/loading.type"

class LSRequest {
  instance: AxiosInstance
  interceptors?: ILSRequestInterceptors
  loadingInstance?: ILoadingInstance
  showLoading: boolean
  constructor(config: ILSRequestConfig) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? true
    // this.loadingInstance = ElLoading.service({ fullscreen: true })
    //从config取出的拦截器是对应实例的拦截器tch
    // )

    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    //添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loadingInstance = ElLoading.service({
            lock: true,
            text: "拼命加载中...",
            background: "rgba(0,0,0,0.8)"
          })
        }
        // console.log("所有实例都有", config)

        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        this.loadingInstance?.close()

        return res
      },
      (err) => {
        return err
      }
    )
  }

  request<T = any>(config: ILSRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      this.instance
        .request<any, T>(config)
        .then((res: any) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
          return err
        })
    })
  }

  get<T = any>(config: ILSRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "GET" })
  }

  post<T = any>(config: ILSRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "POST" })
  }
}

export default LSRequest
